package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.AutoLog;
import com.example.common.Result;
import com.example.pojo.Commodity;
import com.example.pojo.Params;
import com.example.service.CommodityService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/commodity")
public class CommodityController {
    @Resource
    private CommodityService commodityService;

    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Commodity> info = commodityService.findBySearch(params);
        return Result.success(info);
    }
    @PostMapping
    @AutoLog("成功")
    public Result save(@RequestBody Commodity commodity) {
        if (commodity.getId() == null) {
            commodityService.add(commodity);
        } else {
            commodityService.update(commodity);
        }
        return Result.success();
    }
    @DeleteMapping("/{id}")
    @AutoLog("成功删除")
    public Result delete(@PathVariable Integer id) {
        commodityService.delete(id);
        return Result.success();
    }

    @GetMapping("/echarts/bie")
    public Result bie() {
        // 查询出所有图书
        List<Commodity> list = commodityService.findAll();
        Map<String, Long> collect = list.stream()
                .filter(x -> ObjectUtil.isNotEmpty(x.getTypeName()))
                .collect(Collectors.groupingBy(Commodity::getTypeName, Collectors.counting()));
        // 最后返回给前端的数据结构
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(collect)) {
            for (String key : collect.keySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", key);
                map.put("value", collect.get(key));
                mapList.add(map);
            }
        }
        return Result.success(mapList);
    }

    @GetMapping("/echarts/bar")
    public Result bar() {
        // 查询出所有图书
        List<Commodity> list = commodityService.findAll();
        Map<String, Long> collect = list.stream()
                .filter(x -> ObjectUtil.isNotEmpty(x.getTypeName()))
                .collect(Collectors.groupingBy(Commodity::getTypeName, Collectors.counting()));

        List<String> xAxis = new ArrayList<>();
        List<Long> yAxis = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(collect)) {
            for (String key : collect.keySet()) {
                xAxis.add(key);
                yAxis.add(collect.get(key));
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("xAxis", xAxis);
        map.put("yAxis", yAxis);

        return Result.success(map);
    }
}
